package handler

import (
	"222/cache"
	"222/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	name := c.PostForm("name")
	price, _ := strconv.Atoi(c.PostForm("price"))
	if name == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "请将字段填写完整",
		})
		return
	}
	car := model.Car{
		Name:  name,
		Price: price,
	}
	model.DB.Create(&car)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	customer := c.PostForm("customer")
	money, _ := strconv.Atoi(c.PostForm("money"))
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	if cid == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "请将字段填写完整",
		})
		return
	}
	order := model.Order{
		Cid:      cid,
		Money:    money,
		Customer: customer,
	}
	model.DB.Create(&order)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderPage(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var data []model.CarOrder
	redis_key := "order_page_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Debug().Table("orders").
			Select("orders.id as Oid ",
				"orders.money as Money",
				"orders.customer as Customer",
				"cars.name as Name",
				"cars.price as Price").
			Joins("left join cars on cars.id = orders.cid").
			Offset(offset).
			Limit(size).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	oid, _ := strconv.Atoi(c.Query("oid"))
	var data []model.CarOrder
	redis_key := "order_" + strconv.Itoa(oid)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Debug().Table("orders").
			Select("orders.id as Oid ",
				"orders.money as Money",
				"orders.customer as Customer",
				"cars.name as Name",
				"cars.price as Price").
			Joins("left join cars on cars.id = orders.cid").
			Where("orders.id = ?", oid).
			Limit(1).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
}
